package com.bulletelc.apollopre.module.main.center.address.edit;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.NetWorkPath;
import com.bulletelc.apollopre.entity.AddressDetailBean;
import com.bulletelc.apollopre.framework.BasePresenter;
import com.bulletelc.apollopre.utils.MyUtil;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * author: lhl
 * date: 2018/1/24
 * desc: TODO
 */
public class EditAddressPresenter extends BasePresenter<EditAddressContract.View> implements EditAddressContract.Presenter {
    @Override
    public void start() {

    }

    @Override
    public void stop() {

    }

    @Override
    public void addAddress(String json) {
        addAddressImp(json);
    }

    @Override
    public void editAddress(String json,int addressId) {
        editAddressImp(json,addressId);
    }

    @Override
    public void getAddressDetail(int addressId) {
        getAddressDetailImp(addressId);
    }

    @Override
    public void getRegionalData() {
        getRegionalDataImp();
    }

    /**
     * 添加地址
     *
     * @param json
     */
    private void addAddressImp(String json) {
        RequestBody body = RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON), json);
        OkGo.<String>post(NetWorkPath.POST_USER_ADDRESS_CREATE)
                .headers(NetWorkPath.HEADER_KEY_AUTH, MyUtil.getAuthToken(MyApplication.getToken()))
                .upRequestBody(body)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseAddAddress(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorAddAddress(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * 解析添加地址返回的数据
     *
     * @param response
     */
    private void parseAddAddress(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject obj = new JSONObject(response.body().toString());
                JSONObject objMeta = new JSONObject(obj.getString("meta"));
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(objMeta.getString("code").toString())) {
                    if (isViewAttached()) {
                        getView().onSuccessAddAddress();
                    }
                } else {
                    getView().onFailAddAddress(objMeta.getString("msg"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorAddAddress("数据解析有误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailAddAddress(response.body().toString());
            }
        }
    }

    /**
     * 更新地址
     * @param json
     */
    private void editAddressImp(String json,int addressId) {
        RequestBody body = RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON), json);
        OkGo.<String>post(NetWorkPath.POST_USER_ADDRESS_UPDATE+"?id="+addressId)
                .headers(NetWorkPath.HEADER_KEY_AUTH, MyUtil.getAuthToken(MyApplication.getToken()))
                .upRequestBody(body)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseEditAddress(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorEditAddress(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * 解析更新地址返回的数据
     *
     * @param response
     */
    private void parseEditAddress(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject obj = new JSONObject(response.body().toString());
                JSONObject objMeta = new JSONObject(obj.getString("meta"));
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(objMeta.getString("code").toString())) {
                    if (isViewAttached()) {
                        getView().onSuccessEditAddress();
                    }
                } else {
                    getView().onFailEditAddress(objMeta.getString("msg"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorEditAddress("数据解析有误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailEditAddress(response.body().toString());
            }
        }
    }

    /**
     * 获取地址详情
     */
    private void getAddressDetailImp(int addressId) {
        OkGo.<String>get(NetWorkPath.GET_USER_ADDRESS_DETAIL)
                .params("access_token", MyApplication.getToken())
                .params("id", addressId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseAddressDetail(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorAddressDetail(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * 解析地址详情数据
     *
     * @param response
     */
    public void parseAddressDetail(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                org.json.JSONObject obj = new org.json.JSONObject(response.body().toString());
                org.json.JSONObject objMeta = new org.json.JSONObject(obj.getString("meta"));
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(objMeta.getString("code").toString())) {
                    Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
                        @Override
                        public boolean shouldSkipField(FieldAttributes f) {
                            return f.getName().contains("_links");
                        }

                        @Override
                        public boolean shouldSkipClass(Class<?> clazz) {
                            return false;
                        }
                    }).create();

                    AddressDetailBean addressDetailBean = gson.fromJson(obj.getJSONObject("data").toString(), AddressDetailBean.class);
                    if (isViewAttached()) {
                        getView().onSuccessAddressDetail(addressDetailBean);
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailAddressDetail(objMeta.getString("msg"));
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorAddressDetail("解析数据有误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailAddressDetail(response.body().toString());
            }
        }
    }

    /**
     * 获取全国地区数据
     */
    private void getRegionalDataImp() {


    }

}
